<template>
  <div>
    产品详情
    <button @click="getProxy">获取实例对象</button>
    <button @click="btnClick">停止监听</button>
    <div style="height:2000px"></div>
    <div class="hot" ref="target">新鲜好物</div>
    <div class="hot" ref="target2">原生</div>
  </div>
</template>
<script>
/*
useIntersectionObserver
1:导入
import { useIntersectionObserver } from '@vueuse/core'
const {stop}=useIntersectionObserver(target,([{ isIntersecting }], observerElement) => {
        isIntersecting:是否进入可视区域的boolean值
        observerElement：当前的一些配制信息
      },{
        配制信息
        root：相对于谁默认是document
  rootMargin:margin偏移
  threshold:百分比从  0-1之间的值  占比多少才叫进入可视区域，默认值不是0
      })
target:需要监测的dom
stop():停止监听dom
*/
/*
 const ob= new IntersectionObserver(([{ isIntersecting }], observerElement) => {
        isIntersecting:是否进入可视区域的boolean值
        observerElement：当前的一些配制信息
      },{配制})
     ob.observe(dom:需要监听的dom)
     ob.unobserve(dom:需要监听的dom)

*/

// import { useIntersectionObserver } from '@vueuse/core'
import { ref, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
export default {
  setup () {
    // const target = ref(null)
    // const { stop } = useIntersectionObserver(
    //   target,
    //   ([{ isIntersecting }], observerElement) => {
    //     if (isIntersecting) {
    //       console.log('进入', observerElement)
    //     } else {
    //       console.log('离开')
    //     }
    //   },
    //   {
    //     threshold: 0
    //   }
    // )
    // function btnClick () {
    //   stop()
    // }
    // return { target, btnClick }

    // 原生:
    /*
    function fn(){return {a:10,b:20}}
    const {a,b}=fn()
    const {a,b}={a:10,b:20}
    */

    const target2 = ref(null)
    function HmIntersectionObserver (target, callback, option) {
      const ob = new IntersectionObserver(callback, option)
      //
      onMounted(() => {
        ob.observe(target.value)
      })
      onBeforeUnmount(() => {
        stop()
      })

      function stop () {
        ob.unobserve(target.value)
      }
      return { stop }
    }
    const { stop } = HmIntersectionObserver(target2, ([{ isIntersecting }]) => {
      if (isIntersecting) {
        console.log('显示')
      } else {
        console.log('隐藏')
      }
    })
    function btnClick () {
      stop()
    }
    // 获取实例对象
    const { proxy } = getCurrentInstance()
    function getProxy () {
      console.log('实例对象', proxy)
    }

    return { target2, btnClick, getProxy }
  }
}
</script>
<style>
.hot {
  width: 100%;
  height: 100px;
  border: 1px solid red;
}
</style>
